$(function(){
	// var code = GetQueryString("code")||"";
	var code = localStorage.exam_code || "";
	window.exam_code = code;
	// 获取考试信息
	getExamInfo({
		code: code,
		success: function(res){
			if(res.code === 0){
				var data = res.data;
				$(".exam-name").text(data.name);
				$(".exam-status").text("（"+getExamStatus(data.status)+"）");
				$(".begin-time").text(data.begin_time);
				$(".end-time").text(data.end_time);
				if (data.status == 0) {
					$("#call_student").attr("data-error", "考试未开始，不能进行叫号");
					initUploader();
				}
				if (data.status == 1) {
					$("#pickfiles").attr("data-error", "考试进行中，不能导入考生");
					$("#add_student").attr("data-error", "考试进行中，不能新增考生");
					$("#pickfiles").on("click", function(e){
						e.stopPropagation();
						alert("考试进行中，不能导入考生");
					})
					$(".edit-item").attr("data-error", "考试进行中，不能编辑考生信息");
					$(".delete-item").attr("data-error", "考试进行中，不能删除考生");
				}
				if (data.status == 2) {
					$("#pickfiles, #add_student, #change_status, #call_student, .edit-item, .delete-item").attr("data-error", "考试已结束，不能对考试进行任何修改");
					$("#pickfiles").on("click", function(e){
						e.stopPropagation();
						alert("考试已结束，不能对考试进行任何修改");
					})
				}
			}else{
				alert(res.msg);
			}
		},
		fail: function(res){
			var res = JSON.parse(res.responseText)
			alert(res.msg)
		}
	})
	// 获取用户信息
	getUserInfo({
		success: function(res){
			if (res.code == 0) {
				var data = res.data;
				$(".user-name").text(data.username);
			}else{
				alert(res.msg);
			}
		},
		fail: function(res){
			var res = JSON.parse(res.responseText)
			alert(res.msg)
		}
	})
	// 获取学生列表
	var nowPage = 1, pageSize = 10, searchStatus = -1, searchName = '', searchExamNumber = '';
	getStudentListFun();
	window.getStudentListFun = getStudentListFun;
	function getStudentListFun(){
		var prama = {
			page: nowPage,
			size: pageSize,
			code: code,
			success: function(res){
				if(res.code === 0){
					setStudentList(res,nowPage);
				}else{
					alert(res.msg)
				}
			},
			fail: function(res){
				var res = JSON.parse(res.responseText)
				alert(res.msg)
			}
		}
		if(searchStatus > -1){
			prama.status = searchStatus
		}

		if(searchName){
			prama.name = searchName
		}

		if(searchExamNumber){
			prama.exam_number = searchExamNumber
		}
		getStudentList(prama);
	}
	function setStudentList(res,page){
		var results = res.data.results;
		var count = res.data.count;
		var previous = res.data.previous;
		var next = res.data.next;
		var page_count = 10;
		setPagination({
			previous: previous,
			next: next,
			count: count,
			page_count: page_count,
			nowPage: nowPage,
			continueFun: function(){
				$(".student-tr").remove();
				$(results).each(function(index, item){
					var clone = $(".clone-stutr").clone().removeClass("clone-stutr hide").addClass("student-tr");
					clone.attr({"data-id":item.code, "data-name": item.name, "data-sex": item.sex, "data-batch": item.batch, "data-status": item.status, "data-seat": item.seat, "data-examnumber": item.exam_number, "data-paperstype": item.papers_type, "data-papersnumber": item.papers_number, "data-exam": item.exam});
					clone.find(".stu-name").text(item.name);
					clone.find(".stu-number").text(item.exam_number);
					clone.find(".stu-sex").text(item.sex?"女":"男");
					clone.find(".stu-status").text(getStuStatus(item.status));
					$("table.exam-table").append(clone);
				})
				$(".hasnot-table").addClass("hide");
				$(".has-table").removeClass("hide");	
			}
		})
	}
	// 新增加考生
	$(document).on("click", "#add_student", function(e){
		e.stopPropagation();
		var id = $("#stuModal").attr("data-id");
		var error = $(this).attr("data-error");
		if(error){
			alert(error);
			return
		}
		$("#stuModal").find(".modal-title").text("新增考生");
		if(id !== undefined){
			$("#stuModal").find("input[type!=radio]").val("");
			$("#stuModal").find("input[type=radio]").removeAttr("checked");
		}
		$("#stuModal").modal("show").removeAttr("data-id");
	})
	// 点击编辑考生信息
	$(document).on("click", ".student-tr .edit-item", function(e){
		e.stopPropagation();
		var error = $(this).attr("data-error");
		if(error){
			alert(error);
			return
		}
		var id = $(this).parents(".student-tr").attr("data-id");
		var name = $(this).parents(".student-tr").attr("data-name");
		var sex = $(this).parents(".student-tr").attr("data-sex");
		var seat = $(this).parents(".student-tr").attr("data-seat");
		var exam_number = $(this).parents(".student-tr").attr("data-examnumber");
		var papers_number = $(this).parents(".student-tr").attr("data-papersnumber");
		var batch = $(this).parents(".student-tr").attr("data-batch");
		$("#stuModal").find(".modal-title").text("编辑考生信息");
		$("#stuModal").attr("data-id", id);
		$("#stuModal").find("#stu_name").val(name);
		$("#stuModal").find("input[name='sex'][value="+sex+"]").attr("checked", "checked");
		$("#stuModal").find("#stu_seat").val(seat);
		$("#stuModal").find("#stu_exam_number").val(exam_number);
		$("#stuModal").find("#stu_papers_number").val(papers_number);
		$("#stuModal").find("#stu_batch").val(batch);
		$("#stuModal").modal("show");
	})
	//
	function testIsNumber(str){
		var num = '0123456789';
		return str.split('').every(function(item, index){
			return num.indexOf(item) > -1
		})
	} 
	$(document).on("click", "#stuModal .modal-sure", function(e){
		e.stopPropagation();
		var name = $("#stu_name").val().trim();
		var sex = $("input[name='sex']:checked").val();
		var seat = $("#stu_seat").val().trim();
		var exam_number = $("#stu_exam_number").val().trim();
		var papers_number = $("#stu_papers_number").val().trim();
		var papers_type = '身份证';
		var batch = $("#stu_batch").val().trim();
		if(name === ""){
			alert("考生名字不能为空");
		}else if(sex === undefined){
			alert("请先选择考生性别");
		}else if(seat === ""){
			alert("考生座位号不能为空")
		}else if(!testIsNumber(seat)){
			alert("考生座位号必须都是数字")
		}else if(exam_number === ""){
			alert("考生考号不能为空")
		}else if(!testIsNumber(exam_number)){
			alert("考生考号必须都是数字")
		}else if(papers_number === ""){
			alert("考生身份证不能为空")
		}else if(batch === ""){
			alert("考场批次不能为空")
		}else if(!testIsNumber(batch)){
			alert("考场批次必须都是数字")
		}else{
			sex = parseInt(sex);
			seat = parseInt(seat);
			exam_number = parseInt(exam_number);
			batch = parseInt(batch);
			var url = "/api/line_up/candidates/";
			var type = 'POST';
			var id = $("#stuModal").attr("data-id");
			// 如果是编辑考生信息，则切换接口以及方式
			if(id !== undefined){
				url = url + id + "/"
				type = "PUT"
			}
			$.ajax({
				url: url,
				type: type,
	            dataType: "JSON",
                data: {
           	    	name: name,
	              	sex: sex,
	              	seat: seat,
	              	exam_number: exam_number,
	              	papers_number: papers_number,
	              	papers_type: papers_type,
	              	batch: batch,
	              	exam: code
	            },
             	success: function(res){
            	    if(res.code === 0){
	                  getStudentListFun();
	                  $("#stuModal").modal("hide");
	                }else{
	                  alert(res.msg)
	                }
                },  
          	    error: function(res){
	                var res = JSON.parse(res.responseText)
	                alert(res.msg)
                }
			})
		}
	})
	// 删除考生
	function deleteStu(option){
		$.ajax({
			url: "/api/line_up/candidates/"+option.code+"/",
			type: "delete",
			dataType: "JSON",
			success: function(res){
				option.success(res)
			},
			error: function(res){
				option.fail(res)
			}
		})
	}
	$(document).on("click", ".student-tr .delete-item", function(e){
		e.stopPropagation();
		var error = $(this).attr("data-error");
		if(error){
			alert(error);
			return
		}
		var id = $(this).parents(".student-tr").attr("data-id");
		deleteStu({
			code: id,
			success: function(res){
				getStudentListFun();
				// if(res.code === 0){
				// 	getStudentListFun();
				// }else{
				// 	alert(res.msg)
				// }
			},
			fail: function(res){
				var res = JSON.parse(res.responseText)
				alert(res.msg)
			}
		})
	})
	// 切换搜索状态
	$(document).on("click", ".search-form .status-dropdown-menu li" , function(e){
		e.stopPropagation();
		var status = parseInt($(this).attr("data-status"));
		var text = $(this).text();
		$(this).parents(".status-btn-group").find(".status-btn-text").text(text).attr("data-status", status);
		searchStatus = status;
		$(this).addClass("active").siblings().removeClass("active").parents(".status-btn-group").removeClass("open");
	})
	$("#search_student_name").on("change", function(e){
		searchName = $(this).val().trim();
	})
	$("#search_student_number").on("change", function(e){
		searchExamNumber = $(this).val().trim();
	})
	// 点击搜索
	$(document).on("click","#search_stu_btn", function(e){
		e.stopPropagation();
		getStudentListFun();
	})
	// 点击清空搜索
	$(document).on("click", "#clear_search_stu_btn", function(e){
		e.stopPropagation();
		searchStatus = -1; 
		searchName = '';
		searchExamNumber = '';
		$("#search_student_name").val("");
		$("#search_student_number").val("");
		$(".search-form .status-dropdown-menu li").removeClass("active").eq(0).addClass("active");
		$(".search-form .status-btn-text").text("全部");
		getStudentListFun();
	})
	// 修改考生状态
	// 点击修改状态
	$(document).on("click", "#change_status", function(e){
		e.stopPropagation();
		var error = $(this).attr("data-error");
		if(error){
			alert(error);
			return
		}
		var stu = $(".stu-checkbox input:checked").parents("tr");
		if(stu.length === 0){
			alert("请至少选择一名考生");
		}else{
			$("#statusModal").find(".choosed-stu-num").text(stu.length);
			$("#statusModal").modal("show");
		}
	})
	// 切换状态
	$(document).on("click", "#statusModal .status-dropdown-menu li" , function(e){
		e.stopPropagation();
		var status = parseInt($(this).attr("data-status"));
		var text = $(this).text();
		$(this).parents(".status-btn-group").find(".status-btn-text").text(text).attr("data-status", status);
		$(this).addClass("active").siblings().removeClass("active").parents(".status-btn-group").removeClass("open");
	}) 
	// 点击确认修改考生状态
	$(document).on("click", "#statusModal .modal-sure", function(e){
		e.stopPropagation();
		var status = $(this).parents(".modal").find(".status-btn-text").attr("data-status");
		var stu = $(".stu-checkbox input:checked").parents("tr");
		if(status===undefined){
			alert("请先选择状态");
		}else{
			var count = 0;
			status = parseInt(status);
			$("#statusModal").modal("hide");
			$(".loading").removeClass("hide").find(".loading-text").text("修改中...");
			stu.each(function(index,item){
				var id = $(item).attr("data-id");
				$.ajax({
					url: '/api/line_up/candidates/'+id+"/",
					type: "PATCH",
		            dataType: "JSON",
	                data: {
	           	    	status: status
		            },
	             	success: function(res){
	            	    var res = res;
	                },  
	          	    error: function(res){
		                var res = JSON.parse(res.responseText)
	                },
	                complete: function(res){
	                	count++
	                	if(count == stu.length){
							$(".loading").addClass("hide");
							getStudentListFun();
							alert("修改成功");
	                	}
	                }
				})
			})
		}
	})
	// 点击叫号
	$(document).on("click", "#call_student", function(e){
		e.stopPropagation();
		var error = $(this).attr("data-error");
		if(error){
			alert(error);
			return
		}
		$("#callStuModal").modal("show");
	})
	// 确认叫号
	$(document).on("click", "#callStuModal .modal-sure", function(e){
		e.stopPropagation();
		var number = $("#call_student_number").val().trim();
		if(number === ''){
			alert("请先输入叫号数量")
		}else if(!testIsNumber(number)){
			alert("叫号数量必须为数字");
		}else{
			number = parseInt(number);
			$.ajax({
				url: "/api/line_up/call/",
				type: "POST",
				dataType: "JSON",
				data: {
					exam: code,
					number: number
				},
				success: function(res){
					if(res.code === 0){
	                  $("#callStuModal").modal("hide");
	                  window.open("call-stu.html", "_blank");
	                }else{
	                  alert(res.msg)
	                }
				},
				error: function(res){
					var res = JSON.parse(res.responseText)
	                alert(res.msg)
				}
			})
		}
	})


	// 身份证签到部分开始
	function connect() {
        var result = CertCtl.connect();
        var resultObj = JSON.parse(result);
        if (resultObj.resultFlag !=0) {
        	setTimeout(function(){
        		connect()
        	},100)
        }
    }
    function disconnect() {
        var result = CertCtl.disconnect();
    }
    function getStatus() {
        var result = CertCtl.getStatus();
    }
    function readCert() {
        var startDt = new Date();
        var result = CertCtl.readCert();
        var endDt = new Date();

        var resultObj = JSON.parse(result);
        if (resultObj.resultFlag == 0) {
        	var id_card = resultObj.resultContent.certNumber;
			sendSignIn({
				id_card: id_card,
				success: function(res){
					if (res.code == 0) {
						getStudentListFun()
					}
				},
				fail: function(res){
					console.log("签到失败")
				}
			})
        }
    }
    function sendSignIn(option){
    	var prama = {
    		exam: code,
    		id_card: option.id_card
    	}
    	$.ajax({
			url: "/api/line_up/sign_in/",
			type: "POST",
			dataType: "JSON",
			data: prama,
			success: function(res){
				option.success(res)
			},
			error: function(res){
				option.fail(res)
			}
		})
    }
    connect();
    setInterval(function(){
    	readCert()
    }, 1000)
	// 身份证签到部分结速

	// 上一页
	$(document).on("click", "#previous_page:not(.disabled)", function(e){
		nowPage--;
		getStudentListFun();
	})
	// 下一页
	$(document).on("click", "#next_page:not(.disabled)", function(e){
		nowPage++;
		getStudentListFun();
	})
	// 选择某一页
	$(document).on("click", ".page-li:not(.disabled):not(.active)", function(e){
		var that = $(this);
		nowPage = parseFloat(that.text().trim()) || 1;
		getStudentListFun();
	})
})